package vip.rssc.sharding.configs;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;
import java.util.Date;
import java.util.Optional;

/**
 * <p>Description: [TableShardingAlgorithm]</p >
 * Created on 2021年10月21日
 *
 * @author <a href="chenjia@fehorizon.com">CJ</a>
 * @version 1.0
 * Copyright (c) 2021 上海宏信建设发展有限公司
 */
@Slf4j
public class TableShardingAlgorithm implements PreciseShardingAlgorithm<Date> {

    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Date> preciseShardingValue) {
        availableTargetNames.stream().forEach((availableTargetName) -> {
            log.info("actual node table:{}", availableTargetName);
        });
        log.info("logic table name: {}, rout column: {}", preciseShardingValue.getLogicTableName(), preciseShardingValue.getColumnName());
        log.info("column value: {}", preciseShardingValue.getValue());

        // 按年份分表策略
        Date value = preciseShardingValue.getValue();
        String year = String.format("%tY", value);
        String tb_name = preciseShardingValue.getLogicTableName() + "_" + year;
        log.info("tb_name:{}", tb_name);

        Optional<String> availableTargetNameOptional = availableTargetNames.stream().filter(availableTargetName -> availableTargetName.equals(tb_name)).findFirst();
        if(!availableTargetNameOptional.isPresent()) {
            throw new IllegalArgumentException("TableShardingAlgorithm未匹配到真实节点表["+tb_name+"]");
        }
        return availableTargetNameOptional.get();
    }

}
